08. Python 版本说明

优达学城使用的 Python 版本

优达学城的大部分纳米学位课程将专门使用(或者已经使用) Python 3。

为何选择 Python 3

目前,Python 3 中已经具有很多新的功能,没必要再使用 Python 2,除非你使用的是旧版代码。所有新的 Python 代码应该用 Python 3 编写。

Python 2 和 Python 3 之间的主要差别

大部分情况下,Python 2 代码也可以用 Python 3 运行。当然,Python 3 中推出的大部分新功能无法向后兼容。而 Python 2 代码经常运行失败的是 print 语句。

对于大部分的旧版 Python,包括 Python 2,输出功能如下所示:

print "Hello", "world!"
> Hello world!

Python 3 中改成了一个函数。

print("Hello", "world!")
> Hello world!

在 2.6 版中,print 函数通过 __future__ 模块向后移植到 Python 2:

# 在 Python 2.6 及以上版本中
from __future__ import print_function
print("Hello", "world!")
> Hello world!

print 语句在 Python 3 中无法运行。如果你要输出内容,并希望在两个版本的 Python 中都可以,则需要在 Python 2 代码中导入 print_function